<?php

namespace app\api\model\question;

use app\api\model\paper\WrongQuestion;
use app\common\model\question\Question as QuestionModel;
use app\common\library\helper;
use app\common\model\examination\ExaminationLog;
use think\facade\Cache;

/**
 * 简历模型
 */
class Question extends QuestionModel
{
    /**
     * 隐藏字段
     */
    protected $hidden = [];

    //获取关联题库
    public function getQuestion($data, $user)
    {
        foreach ($data as $k => $v) {
            //一级
            $data[$k]['question_number'] = $this->where(['category_id' => $v['category_id'], 'is_delete' => 0])->count();
            $keywords = 'question' . $user->user_id . '1' . $v['category_id'];
            $numbner = 0;
            if (!empty($keywords)) {
                $list = Cache::get($keywords);
                if ($list) {
                    $arr= array_filter($list, function($item) {
                        return empty($item['my_answer']);
                    });
                    $numbner=count($arr);
                }
            }
            $data[$k]['my_question_number'] = $numbner;
            //二级
            if(!empty($v['child'])){
                foreach ($v['child'] as $k1 => $v1) {
                    $data[$k]['child'][$k1]['question_number'] = $this->where(['category_id' => $v1['category_id'], 'is_delete' => 0])->count();
                    $keywords = 'question' . $user->user_id . '1' . $v1['category_id'];
                    $numbner = 0;
                    if (!empty($keywords)) {
                        $list = Cache::get($keywords);
                        if ($list) {
                            $arr= array_filter($list, function($item) {
                                return empty($item['my_answer']);
                            });
                            $numbner=count($arr);
                        }
                    }
                    $data[$k]['child'][$k1]['my_question_number'] = $numbner;
                }
            }
        }
        return $data;
    }

    //获取列表

    public function getList($data, $user)
    {

        $model = $this;
        if (isset($data['keywords']) && $data['keywords']) {
            $list = Cache::get($data['keywords']);

            return $list;
        }
        if ($data['type'] == 2) {
            $keywords = 'question' . $user->user_id . time();
        } else {
            $keywords = 'question' . $user->user_id . $data['type'] . $data['category_id'];
        }
        $list = Cache::get($keywords);
        //答完题清空缓存
        if (!empty($list)) {
            $i=0;
            $count=count($list);
            if(!empty($list)){
                foreach ($list as $k => $v) {
                    if(!empty($v['my_answer'])){
                        $i++;
                    }
                }
            }
            if($i==$count){
                Cache::delete($data['keywords']);
                $list='';
            }
            if (!empty($list)) {
                return $list;
            }

        }

        if (isset($data['limit']) && $data['limit'] > 0) {
            $model = $model->limit((int)$data['limit']);
        }

        if (isset($data['type']) && $data['type']) {
            switch ($data['type']) {
                case 1:
                    $model = $model->orderRaw('sort');
                    break;
                case 2:
                    $model = $model->orderRaw('RAND()');
                    break;
            }
        }
        if (isset($data['category_id']) && $data['category_id']) {
            $model = $model->where('category_id', '=', $data['category_id']);
        }
        $list = $model->with(['knowledge', 'image'])
            ->where('is_delete', '=', 0)
            ->field("*")
            ->select();
//        foreach ($list as $k => $v) {
//            $list[$k]['user_id'] = $user->user_id;//用户ID
//            $list[$k]['answer_state'] = 0;//答题状态0未答题1回答正确2回答错误
//            $list[$k]['my_answer'] = '';//我的答案
//            $list[$k]['time'] = time();
//            $list[$k]['keywords'] = $keywords;
//            $list[$k]['type'] = $data['type'];
//        }
        // 为每个子数组添加新的键
        $list = !empty($list) ? $list->toArray() : [];
        $list =  array_map(function($item) use ($user, $keywords,$data) {
            $item['user_id'] = $user->user_id;//用户ID
            $item['answer_state'] = 0;//答题状态0未答题1回答正确2回答错误
            $item['my_answer'] = '';//我的答案
            $item['time'] = time();
            $item['keywords'] = $keywords;
            $item['type'] = $data['type'];
            return $item;
        }, $list);
        if ($data['type'] == 2) {
            Cache::set($keywords, $list, 259200);
        } else {
            Cache::set($keywords, $list, 1296000);
        }

        return $list;
    }

    public function submitAnswer($data, $user)
    {
        if (!Cache::get($data['keywords'])) {
            throw new BaseException(['msg' => "题目信息不存在"]);
        }
        $list = Cache::get($data['keywords']);

        $WrongQuestion = new WrongQuestion();
        $count=count($list);
        $i=0;
        $score=0;
        $question=[];

        foreach ($list as $k => $v) {
            $i++;
            $question[]=$v['question_id'];
            if($list[$k]['my_answer']==$data['my_answer'] || $v['answer']==$v['my_answer']){
                $score++;
            }
            if ($v['question_id'] == $data['question_id']) {
                $list[$k]['my_answer'] = $data['my_answer'];
                if ($v['answer'] == $data['my_answer']) {
                    $list[$k]['answer_state'] = 1;
                    $WrongQuestion->setCacheDelete(0, $user);
                } else {
                    $list[$k]['answer_state'] = 2;
                    //添加错题
                    $WrongQuestion->addWrong(0, $v['question_id'], $data['my_answer'], $v['answer'], 0, $user);
                }
                if($i==$count && $list[$k]['type']==2){
                    //答题完成
                    $ExaminationLog=new ExaminationLog();
                    $find=$ExaminationLog->where('status',0)->where(['user_id'=>$v['user_id']])->find();
                    $arr=['app_id'=>self::$app_id,'user_id'=>$v['user_id'],'score'=>$score,'duration'=>time()-$v['time'],'question_text'=>json_encode($question,true)];
                    if(!empty($find)){
                        if($find['score']<$score){
                            $ExaminationLog->where('status',0)->where(['user_id'=>$v['user_id']])->delete();
                            $ExaminationLog->save($arr);
                        }
                    }else{
                        $ExaminationLog->save($arr);
                    }
                    Cache::delete($data['keywords']);
                }else if($score==$count && $list[$k]['type']==1){
                    Cache::delete($data['keywords']);
                }
                break;
            }
        }

        if ($list[0]['type'] == 2) {
            Cache::set($data['keywords'], $list, 259200);
        } else {
            Cache::set($data['keywords'], $list, 1296000);
        }
        return true;
    }

    //简历详情
    public function getDetail($hire_id, $user = false)
    {
        $detail = self::detail($hire_id);
        if (!$detail) {
            throw new BaseException(['msg' => "招聘新信息不存在"]);
        }
        $this->addBrowse($hire_id);
        return $detail;
    }

    //添加浏览数
    public function addBrowse($hire_id)
    {
        $this->where('hire_id', '=', $hire_id)->inc('browse_count', 1)->update();
    }

    /**
     * 立即购买：获取订单简历列表
     */
    public static function getOrderCourseListByNow($params)
    {
        // 商品详情
        $course = self::detail($params['hire_id']);
        // 商品列表
        $courseList = [$course];
        foreach ($courseList as &$item) {
            // 商品购买数量
            $item['total_num'] = 1;
            // 商品购买数量
            $item['product_price'] = $item['course_price'];
            // 商品购买总金额
            $item['total_price'] = helper::bcmul($item['course_price'], $item['total_num']);
            //商品id
            $item['product_id'] = $item['hire_id'];
        }
        return $courseList;
    }

    //获取列表
    public function getListByIdsFromApi($courseIds, $course_type)
    {
        $list = $this->with(['image'])
            ->where('course_type', '=', $course_type)
            ->where('is_show', '=', 0)
            ->where('is_delete', '=', 0)
            ->where('hire_id', 'in', $courseIds)
            ->order(['sort' => 'asc', 'hire_id' => 'desc'])
            ->select();
        return $list;
    }
}